<template>
  <div class="container">
    <div class="app-container">
      <el-row :gutter="10">
        <el-col :span="5" class="left">
          <!-- 搜索框 -->
          <el-input
            v-model="queryParams.keyword"
            placeholder="输入员工姓名全员搜索"
            prefix-icon="el-icon-search"
            size="small"
            @input="changeValue"
          />
          <!-- 树形组件 -->
          <el-tree
            ref="deptTree"
            node-key="id"
            :data="depts"
            :props="deptProps"
            default-expand-all
            :expand-on-click-node="false"
            highlight-current
            @current-change="selectNode"
          />
        </el-col>
        <el-col :span="19" class="right">
          <!-- 操作按钮 -->
          <div class="operation">
            <el-button size="mini">群发通知</el-button>
            <div>
              <el-button
                v-permission="'add-employee'"
                size="mini"
                type="primary"
                @click="$router.push('/employee/detail')"
                >添加员工</el-button
              >
              <el-button size="mini" type="default" @click="showExcelDialog = true">excel导入</el-button
              >
              <el-button size="mini" type="default" @click="exportEmployee">excel导出</el-button>
            </div>
          </div>

          <!-- 表格 -->
          <el-table :data="employeeList" :header-cell-style="{ backgroundColor: '#f2f4f7' }">
            <el-table-column type="selection" width="45" />
            <el-table-column
              align="center"
              label="
            头像"
            >
              <template slot-scope="{ row }">
                <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
                <span v-else class="avatar">{{ row.username.slice(0, 1) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="username"
              label="
            姓名"
            />
            <el-table-column
              prop="mobile"
              sortable
              label="
            手机号"
            />
            <el-table-column
              prop="workNumber"
              sortable
              label="
            工号"
            />
            <el-table-column
              label="
            聘用形式"
            >
              <template v-slot="{ row }">
                <span>{{ row.formOfEmployment === 1 ? '正式' : '非正式' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="departmentName"
              label="
            部门"
            />
            <el-table-column
              prop="timeOfEntry"
              sortable
              label="
            入职时间"
            />
            <el-table-column
              label="
            操作"
              width="160"
            >
              <template slot-scope="{ row }">
                <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)"
                  >查看</el-button
                >
                <el-button type="text" style="margin-right: 8px" @click="btnRole(row.id)"
                  >角色</el-button
                >
                <el-popconfirm title="确定要删除该条数据吗？" @onConfirm="deleteEmployee(row.id)">
                  <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页条 -->
          <el-pagination
            style="margin-top: 20px"
            layout="total,prev, pager, next"
            :total="total"
            :current-page.sync="queryParams.page"
            :page-size.sync="queryParams.pagesize"
            @current-change="handleCurrentPageChange"
          />
        </el-col>
      </el-row>
      <!-- 放置导入组件 -->
      <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
      <!-- 放置角色弹层组件 -->
      <el-dialog title="分配角色" :visible.sync="showRoleDialog" width="45%">
        <el-checkbox-group v-model="roleIds">
          <!-- 放置 n 个复选框，要存储的值放在 label 属性里 item.id -->
          <el-checkbox v-for="item in enableRoleList" :key="item.id" :label="item.id">{{
            item.name
          }}</el-checkbox>
        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="assignRoles">确 定</el-button>
            <el-button size="mini" @click="showRoleDialog = false">取 消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getDepartmentListService } from '@/api/department'
import {
  getEmployeeListService,
  exportEmployeeService,
  deleteEmployeeService,
  getEnableRoleListService,
  getEmployeeInfoService,
  assignRolesService
} from '@/api/employee.js'
import { transListToTreeData } from '@/utils/index'
import FileSaver from 'file-saver'
// 导入组件
import ImportExcel from '@/views/employee/components/Import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [],
      deptProps: {
        label: 'name',
        children: 'children'
      },
      employeeList: [], // 员工列表
      queryParams: {
        departmentId: null,
        page: 1, // 当前页
        pagesize: 10, // 当前页大小
        keyword: ''
      },
      total: 0, // 记录员工总数
      showExcelDialog: false, // 用来控制弹层显示
      showRoleDialog: false, // 控制角色弹层
      enableRoleList: [], // 可用角色列表
      roleIds: [], // 用来双向绑定的
      currentUserId: null
    }
  },
  created() {
    this.getDepartment()
  },
  // mounted() {
  //   //证明在组件第一次渲染完毕后，异步数据还未请求到
  //   console.log(2);
  //   console.log(this.queryParams.departmentId);
  //   this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId);
  // },
  methods: {
    // 封装一个调用 api 获取获取组织架构数据的方法
    async getDepartment() {
      const res = await getDepartmentListService()
      this.depts = transListToTreeData(res.data, 0)
      this.queryParams.departmentId = this.depts[0].id
      // 证明在组件第一次渲染完毕后，异步数据还未请求到
      // console.log(1); // 和 mounted 钩子函数打印结果是 2 1

      // 设置选中节点
      // 树组件数据是异步的 可能在 mounted 时数据还未加载完成,所以树形组件可能还未完全初始化或渲染完成
      //  解决方法：使用 $nextTick 确保 DOM 更新完成
      this.$nextTick(() => {
        // 此时意味着 DOM 组件更新完毕，树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      // 这个时候参数记录了 id
      this.getEmployeeList()
    },
    // 选中树节点
    selectNode(data) {
      this.queryParams.departmentId = data.id
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList()
    },
    // 调用api 获取员工列表
    async getEmployeeList() {
      const {
        data: { rows, total }
      } = await getEmployeeListService(this.queryParams)
      this.employeeList = rows
      this.total = total
    },
    // 当前页发生变化触发
    handleCurrentPageChange(val) {
      this.getEmployeeList()
    },
    // 改变输入框内容触发
    changeValue() {
      // 防抖： 单位时间内只执行最后一次
      // this.timer 表示在当前组件实例上赋值了一个 timer 的属性
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    // 导出员工的 excel
    async exportEmployee() {
      const res = await exportEmployeeService() // 导出所有员工的接口
      // console.log(res); // 使用一个npm包 直接将Blob文件下载到本地 file-saver
      // FileSaver.saveAs(Blob对象,文件名称)   下载到浏览器下载的地方
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    // 删除员工
    async deleteEmployee(id) {
      await deleteEmployeeService(id)
      if (this.employeeList.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    // 点击角色按钮触发
    async btnRole(id) {
      const res = await getEnableRoleListService()
      this.enableRoleList = res.data
      // 记录当前点击的 id
      this.currentUserId = id
      const { data: employeeInfo } = await getEmployeeInfoService(id)
      this.roleIds = employeeInfo.roleIds
      this.showRoleDialog = true
    },
    // 点击确定按钮后触发
    async assignRoles() {
      await assignRolesService({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配员工角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  margin: 10px;

  .left {
    padding: 25px !important;

    .el-input {
      width: 224px;
      margin-bottom: 10px;
    }
  }
  .right {
    padding: 20px !important;
    border-left: 1px solid #eaeef4;
    text-align: right;
    .operation {
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
    }
    .avatar {
      display: inline-block;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background-color: #04c9be;
      text-align: center;
      line-height: 30px;
      color: #fff;
    }
  }
}
</style>
